繼昨日,Sign的篇幅跟測試的時間花比較久,因此拆成part 1, 2
function calcurateIv($nonce) {
$hash = hash('SHA256', $nonce);
return strtoupper(substr($hash, 48));
}
calcurateIv('value_nonce');
// result: "4F938A1542F4CC29"
$data = [
"ShopNo" => "BA0026_001",
"OrderNo" => "A202109140001",
"Amount" => 16888,
"CurrencyID" => "TWD",
"PayType" => "A",
"ATMParam" => ["ExpireDate" => "20210921"],
"CardParam" => [],
"ConvStoreParam" => [],
"PrdtName" => "虛擬帳號訂單",
"ReturnURL" => "https://127.0.0.1/Store/Return",
"BackendURL" => "https://127.0.0.1/AutoPush/PushSuccess"
];
看著文件,測來測去運算結果都不是文件上面寫的結果,跑去看範例程式
$padding = 16 - (strlen($data) % 16);
$data .= str_repeat(chr($padding), $padding);
$encrypt = openssl_encrypt($data, 'AES-256-CBC', $key, OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING, $iv);
$result = strtoupper(bin2hex($encrypt));
line 1~2: 塞滿 $data_json 長度,使其可被16整除
line 3 : 進行加密
line 4 : 將 binary 轉成 hex 為可讀文字
而研究時發現一個事情,原來這裡的 message 要把值為 null 的移除
範例程式有個寫法很簡單就能實現
array_filter((array) ($data));
又學到了一招了
看起來我應該也沒有更簡潔的寫法
但需要寫進laravel裡面,還是自己複製貼上然後加點小料,開發者基本上都是這樣 XD
function encryptMessage($data, $key, $iv) {
$data = json_encode(array_filter((array) ($data)));
$padding = 16 - (strlen($data) % 16);
$data .= str_repeat(chr($padding), $padding);
$encrypt = openssl_encrypt($data, 'AES-256-CBC', $key, OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING, $iv);
return strtoupper(bin2hex($encrypt));
}
encryptmessage($data, 'B9F9B96AA4FDB57FF75BDF4AA69B9F9B', '4F938A1542F4CC29');
// result: "9ECC2F0E04475F75FDB8BDC734DB4C8669A2FCAB2ED2A7EF4AF04C1D48238D5954A578A12DEBCC138F763979C9F90B672CBE1B78D17D329281381EAC300D8EF7706716B21920E0E0D7808C77766A50E628838D81786D0FDACE457A77799916B10FF9BE77569CCDC254A57F692684DA06A292EE9451A718B1FE10501C07B67D58062C0EB17AACA70291DA353118D2D15035EA0496C006B6BA4BC5E510B6B790555FEF4CA0F7BBC1BE43E3F3ADF9A7CAFEA847414C7C06A853BE11863C4F3B9128FC03DE12CDA71E8C54DA226DF57D405FC9B53920360C6C8525FA55039BB1727B442AD24F597769A5C52B1A1A7399E85D3218A05E7CCABC912905557E8F7827AD5A33195367E34E81DCA9350BF7F243B942C86C7C9B4C0CA3560BDCAFF76C7FCE9E39AF2AFDCD9C7E233B7A60D9C6EB9E"
那今天就先到這,明天見